<script>
import MySwiper from "@/components/MySwiper/MySwiper.vue";
import my_home_card from "@/components/my_home_card/index.vue";
import my_upload_card from "@/components/my_upload_card/index.vue";
import tabBar from "@/components/TabBar/TabBar.vue";
import Popup from "@/components/popup/popup.vue";
import tips from "@/utils/tips";
import NavBar from "@/components/nav-bar/nav-bar.vue";
import SwitchLang from "@/components/switch-lang/switch-lang.vue";
import UploadSelectPopup from "@/components/upload-select-popup/upload-select-popup.vue";
import {uploadFileServerUrl} from "@/services/office";
import {mapState} from "vuex";
import {getPrinterObj} from "@/services/store/printer";
import {getCanPaper} from "@/utils/utils";
import {updateUserPhone} from "@/services/api";
import {getFilePages} from "@/services/liank";
import {adClick, getAd} from "@/services/ad";

export default {
  name: "index",
  components: {UploadSelectPopup, NavBar, SwitchLang, Popup, MySwiper, my_home_card, my_upload_card, tabBar},
  data() {
    return {
      agreement: false, // 用户协议
      isAgreed: false, // 用户协议已读
      showUpload: false, // 上传文件

      fileName: '', // 上传文件 name
      uploadProgress: 0, // 文件上传进度
      extension: ['doc', 'docx', 'xls', 'xlsx', 'pdf', 'ppx', 'ppt', 'pptx'],
      adList: [], // 广告列表
      showUploadImagePopup: false, // 上传照片

      // document
      document: [
        {name: 'multi_printer_id', icon: 'print-id', url: 'multi_print_id'},
        {name: 'print_registration', icon: 'print-registration', url: 'print_registration'},
        {name: 'print_id_and_registration', icon: 'print-id-and-registration', url: 'print_id_and_registration'},
        {name: 'print_drive', icon: 'print-drive', url: 'print_drive'},
        {name: 'print_business_license', icon: 'print-business-license', url: 'print_business_license'},
      ],

      // toolBox
      toolBox: [
        {name: 'autoSplitPdf', icon: 'auto-split-pdf', url: 'AutoSplitPdf'},
        {name: 'splitPdf', icon: 'split-pdf', url: 'SplitPdf'},
        // {name: 'PDF2image', icon: 'PDF2image', url: 'PDF2Image'},
        // {name: 'PDF2LongImage', icon: 'PDF2long-image', url: 'PDF2LongImage'},
        // {name: 'Word2PDF', icon: 'Word2PDF', url: 'Map2PDF', param: 'word'},
        // {name: 'Excel2PDF', icon: 'Excel2PDF', url: 'Map2PDF', param: 'excel'},
        // {name: 'PPT2PDF', icon: 'PPT2PDF', url: 'Map2PDF', param: 'ppt'},
        // {name: 'mergePdf', icon: 'merge_pdf', param: 'mergePdf'},
      ],

      // 其他文件打印方式列表
      otherDevicePrintingMethods: [
        {name: 'ding', icon: 'ding', param: 'ddword'},
        {name: 'qq', icon: 'qq', param: 'qqword'},
        {name: 'qq_email', icon: 'qq_email', param: 'qqemail'},
        {name: 'wps', icon: 'wps', param: 'wpsword'},
      ],
    }
  },
  computed: {
    ...mapState(['store', "machine", "printer", "machineOnline", "userInfo"]),
    lang() {
      return this.$t('index')
    },
  },
  onLoad(options) {
    const {scene} = options
    // 微信扫码进入
    if (scene) {
      const printerId = decodeURIComponent(scene).split("=")[1]
      if (printerId) {
        this.getPrinterObject(printerId)
      }
    }
    this.getAdData()
    this.getUserLocation() // 获取用户定位
  },
  methods: {
    getCanPaper,
    async getPrinterObject(printerId) {
      const res = await getPrinterObj(printerId)
      if (res.code === 200) {
        const {store, machine, printer} = res.data
        this.$store.commit('setSettings')
        this.$store.commit('setPrinter', printer)
        this.$store.commit('setStore', store)
        this.$store.commit('setMachine', machine)
        this.$store.commit("setMachineOnline")
      }
    },
    // 获取用户当前位置
    getUserLocation() {
      uni.getLocation({
        type: 'gcj02',
        success: (res) => {
          console.log(res)
          this.$store.commit('setLocation', {longitude: res.longitude, latitude: res.latitude})
        }, fail(err) {
          console.log('getLocation', err)
        }
      })
    },

    // get banner
    async getAdData() {
      const banners = await getAd(1)
      console.log("banners -=-==", banners)
      this.adList = banners.data
    },
    async onSwiper(index) {
      if (!this.userInfo.phone) {
        tips.toast(this.otherLang.not_agreement_text, 600);
        setTimeout(() => {
          this.agreement = true;
          this.isAgreed = false
        }, 500);
        return;
      }
      const {id, type, link_url} = this.adList[index]
      const clickData = await adClick(id)
      if (type === 'page') {
        uni.navigateTo({url: `${link_url}?detail=${encodeURIComponent(JSON.stringify(clickData.data))}`})
      }
    },

    // 小程序里扫码
    onScan() {
      // 只允许通过相机扫码
      uni.scanCode({
        autoZoom: true,
        hideAlbum: true,
        autoDecodeCharset: true,
        success: ({path}) => {
          const scene = path.split('?')[1]
          if (scene) {
            const printerId = decodeURIComponent(scene).split('=')[2]
            if (printerId) {
              this.getPrinterObject(printerId)
            } else console.log('没有 printer_id', printerId)
          } else console.log('没有 scene', scene)
        }
      });
    },
    // 选择商家页面进入
    toSelectStore() {
      uni.vibrateShort();
      uni.navigateTo({url: '/pages/select_store/select_store'});
    },
    // 检查用户授权和打印机在线状态
    checkUserAndMachineStatus() {
      // 检查用户是否授权
      if (!this.userInfo.phone) {
        tips.toast(this.otherLang.not_agreement_text, 600);
        setTimeout(() => {
          this.agreement = true;
          this.isAgreed = false
        }, 500);
        return false;
      }

      // 检查打印机是否在线
      if (!this.machineOnline) {
        tips.toast(this.otherLang.not_printer);
        this.$store.commit("setMachineOnline");
        return false;
      }
      return true;
    },
    // 进入打印页面
    priseGoPrintPage(pageName, type) {
      // 检查用户是否授权 和 印机是否在线
      if (!this.checkUserAndMachineStatus()) return;

      const url = type === 'photo' ? `/pages/${pageName}/${pageName}` : `/pages/document/${pageName}`;
      uni.navigateTo({url});
    },

    // 送微信里上传文件 (文件打印)
    onWechatMessagePrint() {
      // 检查用户是否授权 和 印机是否在线
      if (!this.checkUserAndMachineStatus()) return;

      // 选择上传文件
      uni.chooseMessageFile({
        count: 1,
        type: 'file',
        extension: this.extension,
        success: (chooseFileRes) => {
          const {path, name} = chooseFileRes.tempFiles[0]
          this.fileName = name
          this.showUpload = true

          // 服务器上传文件
          const serverTask = uni.uploadFile({
            url: uploadFileServerUrl,
            filePath: path,
            name: 'file',
            success: (res) => {
              console.log('uploadFile success', res)
              const {code, data: {url, page_count}} = JSON.parse(res.data)
              if (code === 200) {
                console.log('uploadFile success', url, page_count)
                uni.navigateTo({
                  url: `/pages/file/print_file?pages=${page_count}&file=${
                      encodeURIComponent(JSON.stringify({url, name}))}`
                })
              }
            },
            complete: () => {
              this.showUpload = false
            }
          })

          // 上传服务器并获取pages 进度条
          serverTask.onProgressUpdate(({totalBytesSent, totalBytesExpectedToSend}) => {
            if (totalBytesExpectedToSend > 0) {
              this.uploadProgress = Math.round((totalBytesSent / totalBytesExpectedToSend) * 100)
            } else {
              this.uploadProgress = 0
            }
          })
        },
        fail: (err) => {
          this.showUpload = false
          console.log(err)
        },
      })
    },

    // 微信里上传照片
    chooseMessage() {
      uni.chooseMessageFile({
        count: 9,
        type: 'image',
        success: (res) => {
          console.log(res.tempFiles)
          uni.navigateTo({url: `/pages/PrintImage/PrintImage?images=${encodeURIComponent(JSON.stringify(res.tempFiles))}`})
          this.showUploadImagePopup = false
        }
      });
    },

    // 本地图片上传或拍照
    chooseImage(index) {
      const sourceTypes = ['camera', 'album'];
      uni.chooseMedia({
        count: 9,
        mediaType: ['image'],
        sourceType: [sourceTypes[index]],
        sizeType: ['original', 'compressed'], // 照片压缩或原图
        success: (res) => {
          console.log(res.tempFiles)
          uni.navigateTo({url: `/pages/PrintImage/PrintImage?images=${encodeURIComponent(JSON.stringify(res.tempFiles))}`})
          this.showUploadImagePopup = false
        },
      });
    },

    // 送微信里上传文件 (文件打印)
    testOnWechatMessagePrint() {
      // 检查用户是否授权 和 印机是否在线
      if (!this.checkUserAndMachineStatus()) return;


      // 选择上传文件
      uni.chooseMessageFile({
        count: 1,
        type: 'file',
        extension: this.extension,
        success: (chooseFileRes) => {
          const {path, name} = chooseFileRes.tempFiles[0]
          this.fileName = name
          this.showUpload = true

          // 服务器上传文件
          const serverTask = uni.uploadFile({
            url: uploadFileServerUrl,
            filePath: path,
            name: 'file',
            success: (res) => {
              console.log('uploadFile success', res)
              const {code, data: {url}} = JSON.parse(res.data)
              if (code === 200) {
                this.uploadToServer(url, name)
              }
            },
          })
          // 转换 PDF 进度条
          serverTask.onProgressUpdate((res) => {
            this.updateProgress(res)
          })
        },
        fail: (err) => {
          this.showUpload = false
          console.log(err)
        },
      })
    },

    // 上传文件到服务器
    async uploadToServer(fileUrl, name) {


      // fileUrl = 'https://office.reqem.cn/static/uploads/print_files/2024-12-21/40.pdf'
      // name = '40.pdf'
      // let pages = 52
      // uni.navigateTo({
      //   url: `/pages/file/print_file?pages=${pages}&file=${
      //       encodeURIComponent(JSON.stringify({url: fileUrl, name}))}`
      // })
      // return


      // 准备打印机需要的信息
      const {machine: {device_id, device_password}, printer: {port, driver_name}} = this
      const jobData = {
        deviceId: device_id,
        deviceKey: device_password,
        devicePort: port,
        printerModel: driver_name,
        dmPaperSize: 9,
        jobFile: fileUrl,
      }

      this.showUpload = true
      try {
        const resPages = await getFilePages(jobData);
        const {code, data} = resPages;
        console.log("成功", resPages);
        if (code === 200) {
          uni.navigateTo({
            url: `/pages/file/print_file?pages=${data.pages}&file=${
                encodeURIComponent(JSON.stringify({url: fileUrl, name}))}`
          })
        }
        // 查看上传进度条
        if (resPages.onProgressUpdate) {
          resPages.onProgressUpdate((res) => {
            const {totalBytesSent, totalBytesExpectedToSend} = res
            if (totalBytesExpectedToSend > 0) {
              this.uploadProgress = Math.round((totalBytesSent / totalBytesExpectedToSend) * 100)
            } else {
              this.uploadProgress = 0
            }
          })
        }
      } catch (error) {
        console.log(error)
        if (error.code === 5021) {
          tips.toast(this.lang.file_size_limit, 3000)
        }
      } finally {
        this.showUpload = false
      }
    },

    // 上传进度条
    updateProgress(res) {
      const {totalBytesSent, totalBytesExpectedToSend} = res
      if (totalBytesExpectedToSend > 0) {
        this.uploadProgress = Math.round((totalBytesSent / totalBytesExpectedToSend) * 100)
      } else {
        this.uploadProgress = 0
      }
    },

    // 用户协议同意
    async getPhoneAndConfirm(e) {
      const {code, errMsg} = e.detail
      if (errMsg === "getPhoneNumber:ok") {
        const resPhone = await updateUserPhone(code)
        if (resPhone.code === 200) {
          this.$store.commit('setUserInfo', resPhone)
          this.agreement = false
        }
      }
    },
    // 阅读用户协议
    onAgreement() {
      uni.navigateTo({url: '/pages/agreement/index'})
      this.agreement = false
    },
    onAgreementRadio() {
      this.isAgreed = !this.isAgreed
    },
    onCancelAgreement() {
      this.agreement = false
    },
  }
}
</script>

<template>
  <view>
    <nav-bar :is-back-icon="false" is-home :page-title="lang.pageName" :is-scrolled="isScrolled"/>

    <!-- 头部商家-->
    <view class="margin-top"/>
    <my-swiper :list="adList" @onClick="onSwiper" :swiper-box-height="360" :swiper-height="300"/>

    <view :class="locale">
      <view class="flex-column gap-30 margin-30">
        <view class="flex-between" style="gap: 24rpx">
          <!-- store info-->
          <view class="flex-1">
            <view class="padding-30 column-between store-box">
              <view class="ltr support-box">
                <!-- 商店名-->
                <view class="flex-center name" v-if="printer.name || store.name">
                  <view>{{ printer.name || store.name }}</view>
                  <view class="state">
                    {{ machineOnline ? '在线' : '离线' }}
                  </view>
                </view>

                <view class="column gap-8">
                  <view
                      v-if="printer.supports_photo === 1 && printer.supports_color && printer.supports_double_side&& getCanPaper(printer.paper_types_supported, 'A3') && getCanPaper(printer.paper_types_supported, 'A4')"
                      class="flex-center support-text">
                    <view>仅支持照片和证件照打印</view>
                  </view>

                  <view class="flex-center params">
                    <view class="flex-center param">
                      <view :class="[ printer.supports_color ? '' : 'color-red']">彩色</view>
                      <view class="flex-center">
                        <image class="param-icon"
                               :src="`/static/globalIcon/${printer.supports_color ? 'tick' : 'close'}.svg`"/>
                      </view>
                    </view>
                    <view class="flex-center param">
                      <view :class="[ printer.supports_double_side ? '' : 'color-red']">双面</view>
                      <image class="param-icon"
                             :src="`/static/globalIcon/${printer.supports_double_side ? 'tick' : 'close'}.svg`"/>
                    </view>
                    <view class="flex-center param">
                      <view :class="[ getCanPaper(printer.paper_types_supported, 'A3') ?'':'color-red']">A3</view>
                      <view class="flex-center">
                        <image
                            class="param-icon"
                            :src="`/static/globalIcon/${getCanPaper(printer.paper_types_supported, 'A3') ? 'tick' : 'close'}.svg`"/>
                      </view>
                    </view>
                    <view class="flex-center param">
                      <view :class="[ getCanPaper(printer.paper_types_supported, 'A4') ? '' : 'color-red']">A4</view>
                      <view class="flex-center">
                        <image
                            class="param-icon"
                            :src="`/static/globalIcon/${getCanPaper(printer.paper_types_supported, 'A4') ? 'tick' : 'close'}.svg`"/>
                      </view>
                    </view>
                  </view>
                </view>
              </view>

              <!-- selected Store-->
              <view class="flex-between">
                <view :class="['flex-center switch', locale]" hover-class="hover" @click="toSelectStore">
                  <view class="common-icon-text" style="color: #1073FF;">{{ lang.switch_devices }}</view>
                  <u-icon name="map-fill" color="#1073FF" size="20"/>
                </view>

                <view/>
              </view>

              <view class="store-box-img">
                <image src="/static/icon/home/store.svg" class="store-img"/>
              </view>
            </view>
          </view>

          <!-- scan-->
          <view @click="onScan" class="flex-1">
            <my_home_card
                :title="lang.common.scan.title" :sub-title="lang.common.scan.desc"
                button-color="linear-gradient(180deg, rgba(74, 158, 255, 0.60) 0%, rgba(50, 131, 236, 0.60) 100%)"
                background-color='linear-gradient(298deg, #117EFF 3.79%, #6DB0FF 83.85%)'
                background-image="/static/icon/home/scan.svg"
                :image-style="{width:'242rpx',height:'168rpx'}"/>
          </view>
        </view>

        <!-- WeChat and image-->
        <view
            v-if="getCanPaper(printer.paper_types_supported, 'A3') || getCanPaper(printer.paper_types_supported, 'A4')"
            class="flex-between" style="gap: 24rpx">
          <!-- 微信-->
          <view class="flex-1" @click="onWechatMessagePrint">
            <my_home_card :title="lang.common.weChat.title" :sub-title="lang.common.weChat.desc"/>
          </view>

          <!-- photo-->
          <view class="flex-1" @click="priseGoPrintPage('print_photo','photo')">
            <my_home_card
                :title="lang.common.photo.title" :sub-title="lang.common.photo.desc"
                button-color="linear-gradient(180deg, rgba(255, 89, 11, 0.60) 0%, rgba(245, 190, 127, 0.60) 100%)"
                background-color='linear-gradient(220deg, #FF961B 11.17%, #FF3000 134.68%)'
                background-image="/static/icon/home/image.svg"
                :image-style="{width:'242rpx',height:'168rpx'}"/>
          </view>
        </view>

        <!-- 功能-->
        <view class="column gap-30"
              v-if="getCanPaper(printer.paper_types_supported, 'A3') || getCanPaper(printer.paper_types_supported, 'A4')">
          <!-- <button @click="showUploadImagePopup=true">试试照片上传</button>-->

          <!-- document-->
          <view class="flex-column hot" style="gap: 32rpx">
            <view>{{ lang.more.document }}</view>
            <view class="flex-row" style="flex-wrap: wrap;row-gap: 30rpx">
              <navigator
                  v-for="(item, index) in document" :key="index" :url="`/pages/document/${item.url}`"
                  hover-class="hover" style="width: 25%">
                <view class="column-center">
                  <view>
                    <image class="icon-90" :src="`/static/icon/document/${item.icon}.svg`"/>
                  </view>
                  <view :class="['icon-text']" style="direction: inherit">{{ lang.common[item.name] }}</view>
                </view>
              </navigator>
            </view>
          </view>

          <!-- toolBox-->
          <view class="flex-column hot" style="gap: 32rpx">
            <view>{{ lang.toolBox.title }}</view>
            <view class="flex-row" style="flex-wrap: wrap;row-gap: 30rpx">
              <!-- 内容-->
              <navigator
                  v-for="(item, index) in toolBox" :key="index" :url="`/pages/ToolBox/${item.url}?param=${item.param}`"
                  hover-class="hover" style="width: 25%">
                <view class="column-center">
                  <view>
                    <image class="icon-90" :src="`/static/toolBox/${item.icon}.svg`"/>
                  </view>
                  <view :class="['icon-text']" style="direction: inherit">{{ lang.toolBox[item.name] }}</view>
                </view>
              </navigator>
            </view>
          </view>

          <!-- 其他软件打印方式-->
          <view class="flex-column hot" style="gap: 32rpx">
            <view>{{ lang.more.printing_methods }}</view>
            <view class="flex-row" style="flex-wrap: wrap;row-gap: 30rpx">
              <!-- 内容-->
              <navigator
                  v-for="(item, index) in otherDevicePrintingMethods"
                  :url="`/pages/analysis/analysis?param=${item.param}`"
                  hover-class="hover" :key="index" style="width: 25%">
                <view class="column-center">
                  <view>
                    <image class="icon-90" :src="`/static/printing_methods/${item.icon}.png`"/>
                  </view>
                  <view :class="['icon-text']">{{ lang.printing_methods[item.name] }}</view>
                </view>
              </navigator>
            </view>
          </view>
        </view>

      </view>
      <tab-bar :current="0"/>
    </view>

    <!-- 用户协议 -->
    <popup :show="agreement" @update:show="agreement = $event">
      <view class="agreement-box">
        <view class="margin-bottom-40 title text-36">感谢使用Ozhas快印！</view>

        <view class="margin-bottom line-height-one-six text-32">我们非常重视您的个人信息安全和隐私保护。</view>

        <view class="margin-bottom line-height-one-six text-32">
          为了更新好的保障您的权益，请您认真阅读
          <text class="color-blue" hover-class="hover" @click="onAgreement">《ozhas快印用户许可协议》</text>
        </view>

        <!-- 同意 radio-->
        <view class="line-height-one-six text-32 margin-bottom-40">
          <label class="flex-center" @click="onAgreementRadio">
            <view style="align-self: flex-start;">
              <radio :checked="isAgreed" color="#117EFF" style="transform:scale(0.8)"/>
            </view>
            <view>
              <text>我已仔细阅读
                <text class="color-blue" hover-class="hover" @click.stop="onAgreement">《ozhas快印用户许可协议》</text>
                ，并同意提供电话号码。
              </text>
            </view>
          </label>
        </view>

        <!-- 同意取消-->
        <view class="flex-between">
          <view class="button">
            <view class="center color-grey bg-white text-32 button-cancel" @click="onCancelAgreement">取消</view>
          </view>

          <view class="button">
            <view class="center text-32 button-agree" :style="{opacity: isAgreed ? 1 : 0.6}">同意
              <button v-if="isAgreed" class="service" open-type="getPhoneNumber" @getphonenumber="getPhoneAndConfirm"/>
            </view>
          </view>
        </view>
      </view>
    </popup>

    <!-- selected image popup -->
    <upload-select-popup
        :show-popup="showUploadImagePopup" @choose-message="chooseMessage" @choose-image="chooseImage"
        @close-popup="showUploadImagePopup = false"/>
    <!-- 上传中-->
    <my_upload_card :upload-progress="uploadProgress" :upload-name="fileName" :show="showUpload"/>
    <view style="height: 200rpx"/>
  </view>
</template>

<style lang="scss" scoped>
.ug-CN {
  .store-box-img {
    left: -20rpx;
    transform: rotateY(180deg);
  }
}

.zh-CN {
  .store-box-img {
    right: -20rpx;
  }
}

.store-box {
  display: flex;
  position: relative;
  overflow: hidden;
  height: 248rpx;
  width: 100%;
  border-radius: 20rpx;
  background: linear-gradient(119deg, #E4EBF4 8.66%, #D5DDE8 93.49%), #D5DDE8;

  .support-box {
    z-index: 2;
  }

  .store-box-img {
    position: absolute;
    bottom: -18rpx;

    .store-img {
      width: 242rpx;
      height: 168rpx;
    }
  }

  .name {
    width: 272rpx;
    font-size: 20px;
    font-weight: 400;
    color: #000;
    animation: marquee 15s linear infinite;
    white-space: nowrap;

    .state {
      margin-left: 10rpx;
      padding: 8rpx 18rpx;
      background: rgba(255, 255, 255, 0.40);
      border-radius: 28rpx;
      color: #5E5E5E;
      font-Size: 24rpx;
      word-wrap: break-word
    }
  }

  @keyframes marquee {
    0% {
      transform: translateX(100%);
    }
    100% {
      transform: translateX(-100%);
    }
  }


  .support-text {
    font-size: 24rpx;
  }

  .params {
    width: fit-content;
    gap: 14rpx;

    .param {
      font-size: 20rpx;
      gap: 4rpx;

      .param-icon {
        width: 20rpx;
        height: 20rpx;
      }
    }
  }

  .switch {
    z-index: 1;
    background-color: #FFFFFF;
    color: #1073FF;
    border-radius: 60rpx;
    padding: 10rpx 14rpx;
    gap: 6rpx
  }
}

.hot {
  padding: 36rpx;
  background-color: #FFFFFF;
  border-radius: 20rpx;
  display: flex;
  flex-direction: column;
  color: #000000;
  font-size: 34rpx;
}

.hot-icon-text {
  color: #696969;
  font-size: var(--default-font-size);
}

.hot-icon-text-ug-CN {
  font-size: var(--ug-font-size);
}

/* 用户协议 */
.agreement-box {
  color: #00000099;
}

/* 题目 */
.agreement-box .title {
  color: #272B34;
  text-align: center;
}

.button {
  width: 40%;
}

.button-cancel {
  height: 94rpx;
  border-radius: 8rpx;
  border: solid 2rpx #ebedf0;
}

.button-agree {
  position: relative;
  background-color: #0E81FC;
  height: 94rpx;
  color: white;
  border-radius: 8rpx;
}
</style>